package com.shirojwt.com.lang;

import org.apache.shiro.ShiroException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author chenguo
 * @date 2021/10/12 3:42 下午
 */

@RestControllerAdvice
public class JwtException {
    @Resource
    private JwtResultMap resultMap;

    @ExceptionHandler(ShiroException.class)
    public JwtResultMap handle401(){
        return resultMap.fail().code(401).message("您没有权限访问！");
    }

    @ExceptionHandler(Exception.class)
    public JwtResultMap globalException(HttpServletRequest request, Throwable e){
        return resultMap.fail().code(getStatus(request).value())
                .message("访问出错，无法访问" + e.getMessage());
    }

    private HttpStatus getStatus(HttpServletRequest request){
        Integer statusCode = (Integer) request.getAttribute("java.servlet.error.status_code");
        if(null == statusCode){
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
